package com.yunze.task.yunze.test;

import com.alibaba.fastjson.JSON;
import com.yunze.apiCommon.utils.VeDate;
import com.yunze.common.mapper.mysql.YrootlowHisMapper;
import com.yunze.common.mapper.mysql.YzCardMapper;

import com.yunze.common.utils.Arith;
import com.yunze.common.utils.yunze.Different;
import com.yunze.common.utils.yunze.ListMapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class TdTestMQ {


    /*@Resource
    private TdbCardFlowHisMapper tdbCardFlowHisMapper;*/
    @Resource
    private YrootlowHisMapper yrootlowHisMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private YzCardMapper yzCardMapper;



    @RabbitHandler
    @RabbitListener(queues = "admin_TdTest_queue")
    public void SynOfferinginfo(String msg) {
        String record_date = "2022-11-07";
        Map<String, Object> fMap = new HashMap<>();

        /*fMap.put("timetype", "1");
        fMap.put("staTime", record_date+" 00:00:00");//指定当天
        fMap.put("endTime", record_date+" 23:59:59");
        fMap.put("GreaterThanZero", "1");*/

        String  day1 = record_date.substring(0,8)+"01";// 1号

        fMap.put("timetype", "1");
        fMap.put("staTime", day1+" 00:00:00");//一号开始
        fMap.put("endTime", record_date+" 23:59:59");
        fMap.put("GreaterThanZero", "1");

       /* List<Map<String,Object>>  list = tdbCardFlowHisMapper.monthGetTop5(fMap);
        List<Map<String,Object>>  rList = GetTop5(list);

        System.out.println(JSON.toJSONString(rList));*/
    }



    public List<Map<String,Object>> GetTop5 (List<Map<String,Object>>  list){
        Map<String, Object> iMap = new HashMap<>();
        List<Map<String,Object>>  rList = new ArrayList<>();
        if(list!=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                Map<String,Object> obj = list.get(i);
                String iccid = obj.get("iccid")!=null?obj.get("iccid").toString():null;
                if(iMap.get(""+iccid)==null){
                    iMap.put(""+iccid,obj);
                    obj.put("used",obj.get("total_show_flow"));
                    obj.remove("total_show_flow");
                    rList.add(obj);
                }
            }
        }
        return  rList;
    }


    @RabbitHandler
    @RabbitListener(queues = "admin_migrateCardFlowHis_queue")
    public void migrateCardFlowHis(String msg) {
        //迁移 用量记录表
        if (StringUtils.isEmpty(msg)) {
            return;
        }

        Map<String, Object> map = JSON.parseObject(msg);
        Object create_time = map.get("create_time");
        Object type = map.get("type");
        Object staTime = map.get("staTime");
        Object endTime = map.get("endTime");

        int StarRow = 0;
        int PageSize = 1000;
       while (true){
           map.put("StarRow",StarRow*PageSize);
           map.put("PageSize",PageSize);
           List<String> iccidArr = yzCardMapper.getIccid(map);
           if(iccidArr!=null && iccidArr.size()>0){
               for (int i = 0; i < iccidArr.size(); i++) {
                   Map<String, Object> pMap = new HashMap<>();
                   pMap.put("iccid",iccidArr.get(i));
                   pMap.put("create_time",create_time);
                   pMap.put("type",type);
                   pMap.put("staTime",staTime);
                   pMap.put("endTime",endTime);
                   sendMigrateEx(pMap);
               }
               StarRow +=1;
           }else {
               break;
           }
       }

    }

    /**
     * 复制 数据到 TDengine
     * @param pMap
     */
    public void migrate(Map<String, Object> pMap){

        List<Map<String,Object>> dataArr = yrootlowHisMapper.getTimeData(pMap);
        if(dataArr!=null && dataArr.size()>0){
            //循环生成 ts
            List<Map<String,Object>> arrs = new ArrayList<>();
            List<String> tsArr = new ArrayList<>();
            for (int i = 0; i < dataArr.size(); i++) {
                Map<String,Object> obj = dataArr.get(i);
                String ts = "";
                while (true){//避免 ts 重复 【ts相当于id，重复时会覆盖】
                    //ts = VeDate.getStringDateSSS();
                    String create_time = obj.get("create_time").toString();
                    ts = create_time+"."+VeDate.getRandom(3);//迁移时 ts = 创建时间再拼接随机数
                    if(!Different.Is_existence(tsArr,ts)){
                        tsArr.add(ts);
                        break;
                    }
                }
                obj.put("ts",ts);
                arrs.add(obj);
            }
            Map<String, Object> saveMap = new HashMap<>();
            saveMap.put("iccid",pMap.get("iccid"));
            int saveCount = 0 ;
            saveMap.put("arrs",arrs);
            /*saveCount += tdbCardFlowHisMapper.batchSave(saveMap);
            log.info("tdbCardFlowHisMapper.batchSave iccid {} saveCount = {}",pMap.get("iccid"),saveCount);*/
        }
    }

    /**
     * 发送 执行
     * @param pMap
     */
    public void sendMigrateEx(Map<String, Object> pMap){
        try {//这里不建议使用递归 翻页 执行 会导致内存溢出！【所以使用队列再次下发】
            Map<String, Object> start_Map = new HashMap<>();
            start_Map.put("pMap",pMap);
            rabbitTemplate.convertAndSend("admin_exchange", "admin.migrateEx.queue", JSON.toJSONString(start_Map), message -> {
                // 设置消息过期时间 30 分钟 过期
                message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                return message;
            });
        }catch (Exception e){
            log.error(" admin.migrateEx.queue 发送指令 异常 {}",e.getMessage());
        }
    }






    @RabbitHandler
    @RabbitListener(queues = "admin_migrateEx_queue",containerFactory = "customContainerFactory")
    public void migrateEx(String msg) {
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        Map<String, Object> map = JSON.parseObject(msg);
        Map<String, Object> pMap = (Map<String, Object>) map.get("pMap");
        migrate(pMap);
    }



    @RabbitHandler
    @RabbitListener(queues = "dlx_admin_migrateEx_queue",containerFactory = "customContainerFactory")
    public void dlxMigrateEx(String msg) {
        //迁移 用量记录表
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        Map<String, Object> map = JSON.parseObject(msg);
        Map<String, Object> pMap = (Map<String, Object>) map.get("pMap");
        migrate(pMap);
    }


}
